//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package project_dao

import (
	"context"
	"errors"
	"fmt"
	"time"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/project_member_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type MemberInfoDbItem struct {
	MemberId      string `bson:"_id"`
	ProjectId     string `bson:"projectId"`
	MemberUserId  string `bson:"memberUserId"`
	RoleId        string `bson:"roleId"`
	CreateTime    int64  `bson:"createTime"`
	UpdateTime    int64  `bson:"updateTime"`
	ProjectWeight uint32 `bson:"projectWeight"`
	LastEventId   string `bson:"lastEventId"`
}

func (item *MemberInfoDbItem) ToMemberInfo(logoUri, displayName string) *project_member_api.MemberInfo {
	return &project_member_api.MemberInfo{
		ProjectId:    item.ProjectId,
		MemberUserId: item.MemberUserId,
		RoleId:       item.RoleId,
		CreateTime:   item.CreateTime,
		UpdateTime:   item.UpdateTime,
		LastEventId:  item.LastEventId,
		LogoUri:      logoUri,
		DisplayName:  displayName,
	}
}

type _MemberInfoDao struct {
	mc *mongo.Collection
}

func newMemberInfoDao(db *mongo.Database) (*_MemberInfoDao, error) {
	mc := db.Collection(db_ns.DB_NS_PROJECT + "member")
	_, err := mc.Indexes().CreateMany(context.Background(), []mongo.IndexModel{
		{
			Keys: bson.D{{"projectId", 1}},
		},
		{
			Keys: bson.D{{"memberUserId", 1}},
		},
	})
	if err != nil {
		return nil, err
	}
	return &_MemberInfoDao{
		mc: mc,
	}, nil
}

func (db *_MemberInfoDao) Insert(ctx context.Context, dbItem *MemberInfoDbItem) error {
	memberId := db.genMemberId(dbItem.ProjectId, dbItem.MemberUserId)
	if dbItem.MemberId == "" {
		dbItem.MemberId = memberId
	} else if dbItem.MemberId != memberId {
		return errors.New("wrong member id")
	}
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_MemberInfoDao) genMemberId(projectId, userId string) string {
	return fmt.Sprintf("%s:%s", projectId, userId)
}

func (db *_MemberInfoDao) Get(ctx context.Context, projectId, memberUserId string) (*MemberInfoDbItem, error) {
	memberId := db.genMemberId(projectId, memberUserId)
	retItem := &MemberInfoDbItem{}
	query := bson.M{"_id": memberId, "projectId": projectId}
	err := db.mc.FindOne(ctx, query).Decode(retItem)
	return retItem, err
}

func (db *_MemberInfoDao) ListProjectByMember(ctx context.Context, memberUserId string) ([]string, error) {
	tmpList, err := db.mc.Distinct(ctx, "projectId", bson.M{"memberUserId": memberUserId})
	if err != nil {
		return nil, err
	}
	retList := []string{}
	for _, tmpId := range tmpList {
		retList = append(retList, tmpId.(string))
	}
	return retList, nil
}

func (db *_MemberInfoDao) ListMemberId(ctx context.Context, projectId string) ([]string, error) {
	query := bson.M{"projectId": projectId}
	tmpList, err := db.mc.Distinct(ctx, "memberUserId", query)
	if err != nil {
		return nil, err
	}
	retList := []string{}
	for _, tmpItem := range tmpList {
		retList = append(retList, tmpItem.(string))
	}
	return retList, nil
}

func (db *_MemberInfoDao) Remove(ctx context.Context, projectId, memberUserId string) error {
	memberId := db.genMemberId(projectId, memberUserId)
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": memberId, "projectId": projectId})
	return err
}

func (db *_MemberInfoDao) RemoveByProject(ctx context.Context, projectId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"projectId": projectId})
	return err
}

func (db *_MemberInfoDao) Exist(ctx context.Context, projectId, memberUserId string) (bool, error) {
	memberId := db.genMemberId(projectId, memberUserId)
	query := bson.M{"_id": memberId, "projectId": projectId}
	count, err := db.mc.CountDocuments(ctx, query)
	if err != nil {
		return false, err
	}
	return count > 0, nil
}

func (db *_MemberInfoDao) ListMember(ctx context.Context, projectId string) ([]*MemberInfoDbItem, error) {
	query := bson.M{"projectId": projectId}
	cursor, err := db.mc.Find(ctx, query)
	if err != nil {
		return nil, err
	}
	retList := []*MemberInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_MemberInfoDao) ListMyProject(ctx context.Context, memberUserId string) ([]*MemberInfoDbItem, error) {
	query := bson.M{"memberUserId": memberUserId}
	cursor, err := db.mc.Find(ctx, query)
	if err != nil {
		return nil, err
	}
	retList := []*MemberInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_MemberInfoDao) ListMemberByProject(ctx context.Context, projectIdList []string) ([]*MemberInfoDbItem, error) {
	query := bson.M{"projectId": bson.M{"$in": projectIdList}}
	cursor, err := db.mc.Find(ctx, query)
	if err != nil {
		return nil, err
	}
	retList := []*MemberInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_MemberInfoDao) ListMemberByProjectAndUser(ctx context.Context, projectIdList []string, memberUerId string) ([]*MemberInfoDbItem, error) {
	memberIdList := []string{}
	for _, projectId := range projectIdList {
		memberId := db.genMemberId(projectId, memberUerId)
		memberIdList = append(memberIdList, memberId)
	}
	query := bson.M{"projectId": bson.M{"$in": projectIdList}, "_id": bson.M{"$in": memberIdList}}
	cursor, err := db.mc.Find(ctx, query)
	if err != nil {
		return nil, err
	}
	retList := []*MemberInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_MemberInfoDao) ListMemberById(ctx context.Context, projectId string, memberUserIdList []string) ([]*MemberInfoDbItem, error) {
	if len(memberUserIdList) == 0 {
		return []*MemberInfoDbItem{}, nil
	}
	memberIdList := []string{}
	for _, memberUserId := range memberUserIdList {
		memberId := db.genMemberId(projectId, memberUserId)
		memberIdList = append(memberIdList, memberId)
	}
	cursor, err := db.mc.Find(ctx, bson.M{"projectId": projectId, "_id": bson.M{"$in": memberIdList}})
	if err != nil {
		return nil, err
	}
	retList := []*MemberInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_MemberInfoDao) CountMemberById(ctx context.Context, projectId string, memberUserIdList []string) (uint32, error) {
	if len(memberUserIdList) == 0 {
		return 0, nil
	}
	memberIdList := []string{}
	for _, memberUserId := range memberUserIdList {
		memberId := db.genMemberId(projectId, memberUserId)
		memberIdList = append(memberIdList, memberId)
	}
	count, err := db.mc.CountDocuments(ctx, bson.M{"projectId": projectId, "_id": bson.M{"$in": memberIdList}})
	return uint32(count), err
}

func (db *_MemberInfoDao) UpdateRole(ctx context.Context, projectId, memberUserId, roleId string) error {
	memberId := db.genMemberId(projectId, memberUserId)
	nowTime := time.Now().UnixNano() / 1e6
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": memberId, "projectId": projectId}, bson.M{"$set": bson.M{"roleId": roleId, "updateTime": nowTime}})
	return err
}

func (db *_MemberInfoDao) UpdateProjectWeight(ctx context.Context, projectId, memberUserId string, weight uint32) error {
	memberId := db.genMemberId(projectId, memberUserId)
	nowTime := time.Now().UnixNano() / 1e6
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": memberId, "projectId": projectId}, bson.M{"$set": bson.M{"projectWeight": weight, "updateTime": nowTime}})
	return err
}

func (db *_MemberInfoDao) CountByRole(ctx context.Context, projectId, roleId string) (uint32, error) {
	query := bson.M{"projectId": projectId, "roleId": roleId}
	count, err := db.mc.CountDocuments(ctx, query)
	if err != nil {
		return 0, err
	}
	return uint32(count), nil
}

func (db *_MemberInfoDao) SetLastEventId(ctx context.Context, projectId, memberUserId, lastEventId string) error {
	memberId := db.genMemberId(projectId, memberUserId)
	nowTime := time.Now().UnixNano() / 1e6
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": memberId, "projectId": projectId},
		bson.M{"$set": bson.M{"lastEventId": lastEventId, "updateTime": nowTime}})
	return err
}
